package cn.csust.net2.manager.server.service.impl;


import java.util.List;


import org.hibernate.SQLQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.csust.net2.manager.client.module.BaseModule;
import cn.csust.net2.manager.shared.exception.BeyondAuthorityException;
import cn.csust.net2.manager.shared.service.VoteCommonService;
import cn.csust.net2.manager.shared.service.VoteService;
import cn.csust.net2.manager.shared.util.ServiceConstant;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;

@Service(value = ServiceConstant.SERVICE_NAME_VOTE)

public class VoteServiceImpl extends VoteCommonServiceImpl implements VoteService{
	
	@Transactional
	@Override
	public boolean saveVoteResultByPaging(PagingLoadConfig config)throws BeyondAuthorityException {
//		VoteResult vr  = new VoteResult();
		Long userID = config.get(BaseModule.STUDENT_NUMBER);
		String stringAnswer = config.get(VoteService.STRINGANSWER);
		Long answerID = config.get(VoteService.VOTEANSWERID); 
		Long voteID = config.get(VoteCommonService.VOTEID);
		long l =getVoteResultDAO().countsBySQL(" select * from `manager`.`voteResult` where userID = "+userID +" and voteID = "+ voteID);		
		if(l>0){
			return false;
		}
		SQLQuery q = getVoteResultDAO().getCurrentSession().createSQLQuery("INSERT INTO `manager`.`voteResult` (`voteID`,`userID`,`answerID`,`stringAnswer`) VALUES (" +voteID+","+userID+","+answerID+","+stringAnswer+")");
		q.executeUpdate();
		return true;
	}
	
	@Transactional
	@Override
	public boolean canVoteByPaging(PagingLoadConfig config)throws BeyondAuthorityException {
	
		Long studentID = config.get(STUDENT_NUMBER);
		Long voteID = config.get(VoteCommonService.VOTEID);		
		
		if(voteID !=null&&studentID!=null){
			//若已投票返回false
			String sqlFind = "SELECT * FROM `manager`.`voteresult` WHERE voteID = " + voteID + " AND userID = " + studentID;
			long s = getVoteResultDAO().countsBySQL(sqlFind);
			if(s>0){
				return false;
			}
			String sqll = "SELECT banjiID FROM `manager`.`banji_vote` WHERE voteID = " + voteID;
			List<Integer> bjList = getVoteDAO().findListBySQL(sqll);
			String sql = "SELECT banjiID FROM `manager`.`student` WHERE studentNumber = " + studentID;
			List<Integer> bjs = getVoteDAO().findListBySQL(sql);
			if(!bjList.isEmpty()&&!bjs.isEmpty()){
				if(bjList.contains(bjs.get(0))){
					System.out.println("有投票权限");
					return true;
				}
			}
		}
		System.out.println("没有投票权限");
		return true;
	}
	


}
